<template>
  <div>
    <slot :rows="rows" :loading="loading" :search="search"></slot>
    <el-row>
      <el-pagination :style="props.style"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="props.pageSizes"
        :page-size="size"
        :layout="props.layout"
        :total="total"/>
    </el-row>
  </div>
</template>

<script>
import _ from 'lodash';
import { FM_GRID_OPTION, MAX_PAGE_SIZE, DEFAULT_PROPS } from "./index.js";

const isInArray = (d, arr) => {
  if (!arr || arr.length == 0) {
    return false;
  }
  for (const a of arr) {
    if (a == d) {
      return true;
    }
  }
  return false;
};

// let _timer = null;
// const delayToRun = func => {
//   clearTimeout(_timer);
//   _timer = setTimeout(func, 50);
// };

export default {
  name: "FmGrid",

  props: {
    url: {
      type: String,
      require: true
    },
    // 请求产生限制
    only: {
      type: Array
    },
    // 请求方法
    method: {
      type: String,
      // post | get
      default: "post"
    },
    // 数据类型
    dataType: {
      type: String,
      // data | params
      default: "data"
    },
    // 传的参数
    params: {
      type: Object
    },
    // 是否修改 router
    route: {
      type: Boolean,
      default: false
    },
    // 参数
    props: {
      type: Object,
      default() {
        return DEFAULT_PROPS;
      }
    }
  },

  data() {
    return {
      page: 1,
      size: 10,
      total: 0,
      loading: false,
      rows: []
    };
  },

  beforeMount(){
    this.init();
  },

  mounted() {
    this.$nextTick(this.search);
  },

  methods: {
    checkParams() {
      if (this.method == "get") {
        this.dataType = "params";
      }
      if (!this.url) {
        throw new Error("url不能为空！");
      }
    },

    getOptions() {
      return this.$options[FM_GRID_OPTION] || {};
    },

    getProps() {
      return this.props;
    },

    getPage(pms) {
      if (!pms) {
        pms = this;
      }
      const props = this.getProps();
      return pms[props.page];
    },

    getSize(pms) {
      if (!pms) {
        pms = this;
      }
      const props = this.getProps();
      return pms[props.size];
    },
    // 初始化
    init() {
      const options = this.getOptions();
      for(const k in options){
        const option = options[k];
        if(!this[k]){
          this[k] = _.clone(option);
        }else{
          _.assign(this[k],option);
        }
      }
    },

    /**
     * 获取所有的请求参数
     */
    queryParams() {},

    /**
     * 数据中获取行
     */
    getRows(data = {}){
      const props = this.getProps();
      const dt = (props.rows||'').split('.');
      let rtn = [];
      for(let i = 0; i < dt.length; i++){
        if(i == 0){
          rtn = data;
        }
        if(i + 1 == dt.length){
          rtn = rtn[dt[i]] || [];  
          break;
        }
        rtn = rtn[dt[i]] || {};
      }
      return rtn;
    },

    /**
     * 数据中
     */
    getTotal(data = {}){
      const props = this.getProps();
      const dt = (props.total||'').split('.');
      let rtn = 0;
      for(let i = 0; i < dt.length; i++){
        if(i == 0){
          rtn = data;
        }
        if(i + 1 == dt.length){
          rtn = rtn[dt[i]] || 0;  
          break;
        }
        rtn = rtn[dt[i]] || {};
      }
      return rtn;
    },

    getRouteParams() {
      const props = this.getProps();
      const { query } = this.$route;
      const qry = Object.assign({}, query);
      if (this.only && Array.isArray(this.only) && this.only.length > 0) {
        for (let q in qry) {
          if (q == props.page || q == props.size) {
            continue;
          }
          if(!isInArray(q,this.only)){
            delete qry[q];
          }
        }
      }
      return qry;
    },

    /**
     * 完成后延时
     */
    cpt(){
      setTimeout(() => {
        this.loading = false;
      }, 500);
    },

    search(params = {}, pg) {
      // page 和size 都不会出现为 0 的情况
      const props = this.getProps();
      this.checkParams();
      let page = pg || this.getPage(params);
      let size = this.getSize(params);
      if (this.route) {
        const query = this.getRouteParams();
        page = page || query.page;
        size = size || query.size;
      }
      this.page = parseInt(page) || this.page;
      this.size = parseInt(size) || this.size;
      if (this.page <= 0) {
        this.page = 1;
      }
      if (this.size < 1 || this.size > MAX_PAGE_SIZE) {
        this.size = 10;
      }
      console.log(this);

      // delayToRun(() => {
        params = { ...params, ...this.params, [props.page]: this.page,[props.size]: this.size };
        this.loading = true;
        this.$axios({
          url: this.url,
          method: this.method,
          [this.dataType]: params,
          paramsSerializer: props.paramsSerializer
        })
          .then(dt => {
            const {data,status} = dt;
            if (status !== 200) return;
            this.rows = this.getRows(data);
            this.$emit("init-data", this.rows);
            this.total = this.getTotal(data);
            this.cpt();
          })
          .catch(this.cpt);
      // });
    },
    handleSizeChange(size) {
      const props = this.getProps();
      this.search({ [props.size]:size });
    },

    handleCurrentChange(page) {
      const props = this.getProps();
      this.search({ [props.page]:page });
    }
  }
};
</script>

